package com.ostrich.a2104shopping.ui.home.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.ostrich.a2104shopping.R;
import com.ostrich.a2104shopping.databinding.ItemHomeCategoryBinding;
import com.ostrich.a2104shopping.ui.home.entity.CategoryEntity;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/6 09:08
 * @Description : CategoryAdapter
 */
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder> {
    private List<CategoryEntity> mCategoryEntities = new ArrayList<>();


    //追加数据
    public void setData(List<CategoryEntity> list){
        if(list == null || list.size() == 0){
            return;
        }
        mCategoryEntities.addAll(list);
        notifyDataSetChanged();
    }

    //刷新数据
    public void refreshData(List<CategoryEntity> list){
        if(list == null || list.size() == 0){
            return;
        }
        mCategoryEntities.clear();
        mCategoryEntities.addAll(list);
        notifyDataSetChanged();
    }

    //填充一条数据
    public void addData(CategoryEntity category){
        mCategoryEntities.add(category);
        notifyItemInserted(mCategoryEntities.size()-1);
    }
    //删除数据
    public void deleteData(int position){
        mCategoryEntities.remove(position);
        notifyItemRemoved(position);
    }

    //修改数据
    public void updateData(int position,CategoryEntity category){
        CategoryEntity categoryEntity = mCategoryEntities.get(position);
        categoryEntity.setCategory_name(category.getCategory_name());
        categoryEntity.setCategory_icon(category.getCategory_icon());
        notifyItemChanged(position);
    }









    @NonNull
    @Override
    public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemHomeCategoryBinding itemHomeCategoryBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_home_category, parent, false);
        return new CategoryViewHolder(itemHomeCategoryBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
        holder.mItemHomeCategoryBinding.setCategory(mCategoryEntities.get(position));
    }

    @Override
    public int getItemCount() {
        return mCategoryEntities.size();
    }

    class  CategoryViewHolder extends RecyclerView.ViewHolder{
        private ItemHomeCategoryBinding mItemHomeCategoryBinding;


        public CategoryViewHolder(ItemHomeCategoryBinding mItemHomeCategoryBinding) {
            super(mItemHomeCategoryBinding.getRoot());
            this.mItemHomeCategoryBinding = mItemHomeCategoryBinding;
        }
    }
}
